#include <basesocket.h>
#include <cerrno>
//#include <iphlpapi.h>

#ifdef _WIN32
#pragma comment( lib, "ws2_32.lib")
#endif /* _WIN32 */

std::string BaseSocket::ipToString(sockaddr_in addr)
{
#ifdef _WIN32
    std::string strAcceptIp = inet_ntoa(addr.sin_addr);
    return strAcceptIp;
#else
    char ip[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &(addr.sin_addr), ip, INET_ADDRSTRLEN);

    return std::string(ip);
#endif // _Win32


}

BaseSocket::BaseSocket(std::function<void(int, std::string)> onError, SocketType sockType, int socketId) : sock(socketId)
{
    networkInitial();
    if (socketId < 0)
    {
        if ((this->sock = socket(AF_INET, sockType, 0)) < 0)
        {
            onError(errno, "Socket creating error.");
        }
    }
}

void BaseSocket::Close()
{
    if(isClosed) return;

    isClosed = true;
#ifdef _WIN32
    closesocket(this->sock);
#else
    close(this->sock);    
#endif // _WIN32

}

std::string BaseSocket::remoteAddress()
{
    return ipToString(this->address);
}

int BaseSocket::remotePort()
{
    return ntohs(this->address.sin_port);
}
